<template>
  <el-input v-model="data.message"/>
  <el-button @click="send">发送</el-button>
  <el-button @click="closeWebsocket">关闭连接</el-button>
</template>

<script setup>
import {useTokenStore} from "../stores/token.js"
import {reactive} from "vue";
const tokenStore = useTokenStore()
const data = reactive({
  user:JSON.parse(localStorage.getItem('localStorageUser')),
  message:""
})
let websocket = null;

const username = data.user.name
if ("WebSocket" in window){
  websocket = new WebSocket('ws://localhost:9090/ws/'+username);
}else {
  alert("您的浏览器不支持WebSocket");
}

websocket.onerror = function(){
  console.log("连接失败");
};

websocket.onopen = function(){
  websocket.send("这是来自客户端的消息" + new Date());
  console.log("连接成功");
};

websocket.onmessage = function(event){
  console.log(event.data);
};

websocket.onclose = function(){
  console.log("连接关闭");
};

window.onbeforeunload = function(){
  websocket.close();
}

const send = () => {
  const message = data.message;
  websocket.send(message);
}

const closeWebsocket = () => {
  websocket.close();
}

</script>